package com.example.librarymanagementsystem.config;

import com.example.librarymanagementsystem.model.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    @Autowired
    private ObjectMapper mapper;
    //什么请求需要处理      true——所有请求都处理       false——所有请求都不处理
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
       return true;
    }

    @SneakyThrows
    @Override
    /**
     * 写入响应的数据
     */
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
       if(body instanceof Result){
           return body;
       }
       if(body instanceof String){
           //如果是字符串，转成json字符串再返回，否则可能会产生类型转换异常
            return mapper.writeValueAsString(Result.success(body));
       }
        return Result.success(body);
    }
}
